<template>
    <div class="common-layout">
        <!-- <el-container> -->
        <el-header class="el-header">
            <h2>车站设备维修五信息管理系统</h2>
            <div class="user-box">
                <el-icon>
                    <User />
                </el-icon>
                <div class="realname-box">{{ realname }}</div>
                <el-icon v-show="isDown" @click="realNameIconChang">
                    <ArrowDown />
                </el-icon>
                <el-icon v-show="isUp" @click="realNameIconChang">
                    <ArrowUp />
                </el-icon>
                <transition name="el-zoom-in-left">
                <div v-show="lbpShow" class="logout-box-parent" @mouseleave="hideChangeBox">
                    <div class="change-ps son" @click="editUser('update')">用户信息</div>
                    <div class="logout-box son"
                        @click="logout(useStore.userSessionInfo.SESSION_ID, useStore.userInfo.PERSONID)">退出登录</div>
                </div>
                </transition>
            </div>
        </el-header>
        <el-container>
            <el-aside>
                <div class="menu-btn-box">
                    <div class="menu-box " :class="{ active: isMenuActive }" @click="toggleMenu" title="菜单">
                        <el-icon>
                            <Menu />
                        </el-icon>
                    </div>
                    <div class="favorites-box" :class="{ active: isFavoritesActive }" @click="toggleFavorites"
                        title="收藏">
                        <el-icon>
                            <Star />
                        </el-icon>
                    </div>
                    <div class="search-box" :class="{ active: isSearchActive }" @click="toggleSearch" title="搜索">
                        <el-icon>
                            <Search />
                        </el-icon>
                    </div>
                </div>
                <div class="menu-info-box" v-show="isMenuActive">
                    <MenuList v-for="(item, i) in useStore.menuList" :key="i" :item="item" />
                </div>
                <div class="favorites-info-box" v-show="isFavoritesActive">
                    <div v-if="useStore.userCollect.length">
                        <CollectList v-for="(item, i) in useStore.userCollect" :key="i" :item="item" />
                    </div>
                </div>
                <div class="search-info-box" v-show="isSearchActive">
                    <el-input class="search-input" v-model="searchInput" placeholder="Please input" clearable
                        @input="searchChange" />
                    <div class="search-res">
                        <SearchLinks v-for="(item, i) in searchResLinks" :key="i" :item="item" />
                    </div>
                </div>
            </el-aside>
            <el-main>
                <div class="tabs-box">
                    <Tabs />
                </div>
                <div class="session-box">
                    <Session />
                </div>
            </el-main>
        </el-container>
        <!-- </el-container> -->
        <Drawer ref="drawerRef" :title="title" :size="size" @submit="editSubmit(submitType, editForm)"
            @cancel-submit="resetForm">
            <el-form :model="editForm" ref="updateFormRef" :rules="rules">
                <el-form-item label="ID" :label-width="formLabelWidth">
                    <el-input v-model="editForm.ID" autocomplete="off" disabled />
                </el-form-item>
                <el-form-item label="人员号" :label-width="formLabelWidth" prop="PERSONID">
                    <el-input v-model="editForm.PERSONID" autocomplete="off" />
                </el-form-item>
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="USERNAME">
                    <el-input v-model="editForm.USERNAME" autocomplete="off" />
                </el-form-item>
                <el-form-item label="姓名" :label-width="formLabelWidth" prop="REALNAME">
                    <el-input v-model="editForm.REALNAME" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" prop="PASSWORD">
                    <el-input v-model="editForm.PASSWORD" autocomplete="off" type="password" show-password />
                </el-form-item>
                <el-form-item label="备注" :label-width="formLabelWidth">
                    <el-input v-model="editForm.REMARK" autocomplete="off" />
                </el-form-item>
                <el-form-item label="人员组" :label-width="formLabelWidth" prop="PERSONGROUP">
                    <el-select v-model="editForm.PERSONGROUP" placeholder="请选择班组" @visible-change="changePg">
                        <el-option label="" value="" />
                        <el-option v-for="item in useStore.pgs" :label="item.PGNAME" :value="item.PERSONGROUP" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth" prop="STATUS">
                    <el-select v-model="editForm.STATUS" placeholder="状态">
                        <el-option label="活动" :value=1 />
                        <el-option label="不活动" :value=0 />
                    </el-select>
                </el-form-item>
            </el-form>
        </Drawer>
        <IsRenewTokenDialog ref="isRenewTokenDialogRef" :rtMsg="rtMsg" @isRenewToken="isRenewToken">
        </IsRenewTokenDialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount,} from 'vue'


import { mainStore } from '@/stores/store'
import { useRouter } from 'vue-router'
import { removeToken } from '@/utils/token'
import MenuList from '@/views/MenuList.vue'
import Tabs from '@/views/Tabs.vue'
import Session from '@/views/Session.vue'
import Drawer from '@/components/Drawer.vue'
import CollectList from '@/views/CollectList.vue'
import SearchLinks from '@/views/SearchLinks.vue'
import IsRenewTokenDialog from '@/components/IsRenewTokenDialog.vue'
import { getPg, handleUser } from '@/utils/adminApi/usrs'
import { msgOpen } from '@/utils/msg'
import { encryptPassword } from '@/utils/enctyption'
import { reSearchUser, userLogout, needRenewToken } from '@/utils/api'
import { objCopy } from '@/utils/objCopy'
import { isEqual } from '@/utils/objIsEqual'
import { xfjcStore } from '@/stores/jcStore'
import { amddStore } from '@/stores/amddStore';
import { io } from "socket.io-client" // 引入socket.io-client模块




const router = useRouter()
const useStore = mainStore()
const useJcStore = xfjcStore()
const useAmddStore = amddStore()

/**
 * 切换菜单
 */

let realname = useStore.userInfo.REALNAME
let isDown = ref(true)
let isUp = ref(false)
let lbpShow = ref(false)
let isMenuActive = ref(true)
let isFavoritesActive = ref(false)
let isSearchActive = ref(false)
let searchInput = ref(null)
let searchResLinks = ref([])

//变更用户信息
let title = ref("")
let size = ref("35%")
let formLabelWidth = ref('80')
let drawerRef = ref(null) //组件ref
let oldUserInfo = reactive({
    ID: '',
    PERSONID: '',
    USERNAME: '',
    REALNAME: '',
    PASSWORD: '',
    REMARK: '',
    PERSONGROUP: '',
    STATUS: ''
}) //用于存储未修改前用户信息
let editForm = reactive({
    ID: '',
    PERSONID: '',
    USERNAME: '',
    REALNAME: '',
    PASSWORD: '',
    REMARK: '',
    PERSONGROUP: '',
    STATUS: ''
})
let submitType = ref('')
//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    PERSONID: [
        { required: true, message: '请输入人员号', trigger: 'blur' },
    ],
    USERNAME: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    REALNAME: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    PASSWORD: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    PERSONGROUP: [
        { required: true, message: '请选择班组', trigger: 'blur' },
    ],
    STATUS: [
        { required: true, message: '请选择状态', trigger: 'blur' },
    ]
})

//获取班组信息
const changePg = async () => {
    if (!useStore.pgs.length) {
        let pgs = await getPg()
        useStore.setPgs(pgs.datas.pgs)
    }
}

/**
 * 编辑用户信息
 * @param {String} type 处理类型
 */
const editUser = (type) => {
    submitType.value = type
    drawerRef.value.open()
    if (type === 'update') {
        title.value = "编辑"
        editForm = useStore.userInfo
        oldUserInfo = objCopy(useStore.userInfo, oldUserInfo)
    }
}

//重置表单
const resetForm = () => {
    useStore.userInfo = objCopy(oldUserInfo, useStore.userInfo)
}

/**
 * 处理用户方法
 * @param {Object} data 更新用户表单对象
 * @param {String} type 处理类型
 */
const editSubmit = async (type, data) => {
    // console.log(data.PASSWORD);
    submitType.value = type
    if (type === 'update') {
        updateFormRef.value.validate(async (valid) => {
            if (!valid) {
                return false
            } else {
                let isChange = isEqual(data, oldUserInfo)
                // console.log(isChange)
                if (isChange.length) {
                    let psIsChange = ref(false)
                    isChange.forEach((item) => {
                        if (item.prop === 'PASSWORD') {
                            psIsChange.value = true
                        }
                    })
                    data.PASSWORD = psIsChange.value ? encryptPassword(data.PASSWORD) : data.PASSWORD//密码加密 
                    drawerRef.value.showLoading()
                    try {
                        let newUser = await handleUser(type, data, psIsChange.value)
                        let resNewUser = await reSearchUser(data.USERNAME)
                        // console.log(resNewUser)                    
                        newUser.status && resNewUser.status ? msgOpen(newUser.msg, 'success') : msgOpen(newUser.msg)
                        if (resNewUser.status) useStore.setUserInfo(resNewUser.resDatas.changedNewUser[0])
                        // console.log(useStore.userInfo)                    
                    } catch (err) {
                        if (err.code) msgOpen(err.message)
                        // console.log(err)                    
                    } finally {
                        drawerRef.value.hideLoading()
                        drawerRef.value.close()
                    }
                } else {
                    msgOpen('未修改任何信息！')
                }
            }
        })
    }
}




//切换user-box内的图标及展示已退出菜单
const realNameIconChang = () => {
    isDown.value = !isDown.value
    isUp.value = !isUp.value
    !isDown.value && isUp.value ? lbpShow.value = true : lbpShow.value = false
}
const hideChangeBox = () => {
    lbpShow.value = false
    isDown.value = !isDown.value
    isUp.value = !isUp.value
}

//切换菜单、收藏夹、搜索
const toggleMenu = () => {
    if (!isMenuActive.value) {
        isMenuActive.value = true
        isFavoritesActive.value = false
        isSearchActive.value = false
    }
}
const toggleFavorites = () => {
    if (!isFavoritesActive.value) {
        isFavoritesActive.value = true
        isMenuActive.value = false
        isSearchActive.value = false
    }
}
const toggleSearch = () => {
    if (!isSearchActive.value) {
        isSearchActive.value = true
        isFavoritesActive.value = false
        isMenuActive.value = false
    }
}

/**
 * 退出登录
 * @param sessionid 会话id
 * @param personid 人员id
 * @param type 退出类型

 */
const logout = async (sessionid, personid, type = "LOGOUT") => {
    await userLogout(sessionid, personid, type)
    clearStore()
    router.push("./login")
}

const clearStore = () => {
    removeToken()
    useStore.clearUserInfo()
    useStore.clearMenuList()
    useStore.clearOnlySubDirs()
    useStore.clearAllSubTabList()
    useStore.clearPgs()
    useStore.clearDirs()
    useStore.clearUserCollect()
    useStore.clearLinkRoutes()
    useStore.clearUserSessionInfo()
    useStore.clearNeedAddAndNeedDelAuthDirsMidd()
    useStore.clearOldAuthDirsMidd()
    useJcStore.clearLinesInfo()
    useJcStore.clearSpecialtiesInfo()
    useJcStore.clearArea2Info()
    useJcStore.clearGccStations()
    useJcStore.clearCrtStations()
    useJcStore.clearSignLinesInfo()
    useJcStore.clearRcSpecialtiesInfo()
    useAmddStore.clearStations()
    useStore.toggleHomeShow('/xfjc/index/home')
}

//搜索组件
const searchChange = () => {
    setTimeout(() => {
        if (searchInput.value.length) {
            //用于记录查询结果是否有链接
            let searchResHasLinks = ref(false)
            //每次输入时清空searchResLinks数组
            searchResLinks.value = []
            useStore.linksRoutes.forEach(item => {
                let sarchLinkObj = reactive({
                    PATH: "",
                    TITLE: ""
                })
                if (item.meta.title.includes(searchInput.value)) {
                    sarchLinkObj.PATH = item.path
                    sarchLinkObj.TITLE = item.meta.title
                    //查询是否已存在于searchResLinks数组中
                    let hasArr = searchResLinks.value.some((v) => {
                        return v.PATH === sarchLinkObj.PATH
                    })
                    if (!hasArr) searchResLinks.value.push(sarchLinkObj)
                }
            })
            //没有搜索结果处理
            searchResHasLinks.value = searchResLinks.value.length ? true : false
            if (!searchResHasLinks.value) {
                searchResLinks.value.push({
                    TITLE: "暂无相关链接",
                    PATH: ""
                })
            }
        } else {
            searchResLinks.value = []
        }
    }, 1000)
}

// 续期token
let rtMsg = ref("") //续期信息
let isResRt = ref(false) //是否响应续期
let isRenewTokenDialogRef = ref(null)
const isRenewToken = async (data) => {
    // console.log(data)
    isResRt.value = true
    if (!data) {
        logout(useStore.userSessionInfo.SESSION_ID, useStore.userInfo.PERSONID)
        socket.close()
        isResRt.value = false
    } else {
        socket.emit("needRenewToken", {
            msg: "续期token",
            needRenewtoken: 1
        })
        let resData = await needRenewToken(data)
        // console.log(resData)
        msgOpen(resData.msg, 'success')
        isResRt.value = false
    }
}

// 创建socket.io实例
const socket = io(import.meta.env.VITE_SOCKET_URL, { withCredentials: true })
// 监听连接事件
socket.on('connect', () => {
    // console.log('已连接到服务器');
    msgOpen('已连接到服务器', 'success')
});
// 监听消息事件
socket.on('renewToken', (data) => {
    // console.log('收到服务器消息:', data);
    if (data.status === 401) {
        rtMsg.value = data.msg
        isRenewTokenDialogRef.value.open()
    }
});

/*

// 监听beforeunload事件(页面关闭时，用户点击退出登录直接关闭页面)
// let isClose = ref(false)

// 监听visibilitychange事件,判断关闭或刷新行为
// const handleVisibilityChange = () => {
//     if(document.visibilityState === 'hidden'){
//         // 页面变为隐藏状态（可能是关闭或切换标签页）
//         isClose.value = true
//     }
//     if(document.visibilityState === 'visible'){
//         // 页面重新可见（可能是从隐藏状态返回）
//         isClose.value = false
//     }
// }

// 监听beforeunload事件,关闭或刷新时弹框提示
const handleBeforeUnload = (e) => {
    e.preventDefault()
}

// 监听pagehide事件,判断关闭或刷新行为,如果是关闭行为,则发送请求
// const handlePagehide = () => {
//     console.log(document.visibilityState)
//     if(document.visibilityState === 'hidden'){
//         isClose.value = true    
//     }else if(document.visibilityState === 'visible'){
//         isClose.value = false    
//     }
//     console.log(isClose.value)
// }

// const handlePageshow = () => {
//     isClose.value = false
//     console.log(isClose.value)
//     console.log(document.visibilityState)
// }


// 监听unload事件(页面关闭时，用户退出登录直接关闭页面,刷新也会触发unload事件)

const handleUnload = () => {
    let baseURL = import.meta.env.VITE_BASE_URL
    let data = new Blob([JSON.stringify({
        sessionid: useStore.userSessionInfo.SESSION_ID,
        personid: useStore.userInfo.PERSONID,
        type: "LOGOUT-BEFOREUNLOAD"
    })], { type: 'application/json' })

    // 检测是否是关闭行为而非刷新
    // 使用现代API替代已弃用的performance.navigation.type
    // const navEntries = performance.getEntriesByType('navigation');
    // const navigationType = navEntries.length > 0 ? navEntries[0].type : '';
    // // navigationType为'navigate'表示正常加载，'reload'表示刷新，'back_forward'表示通过历史记录导航
    // // 结合isClose.value判断是否是关闭标签页/窗口
    // // if (isClose.value && navigationType !== 'reload') {
    // console.log(navEntries)
    // console.log(navigationType)
    // isClose.value = navigationType !== 'reload' ? true : false
    // if(isClose.value){
        clearStore()
        navigator.sendBeacon(`${baseURL}/index/userLogout`, data )
    // }
}

// 监听beforeunload、unload事件
onMounted(() => {
    // window.addEventListener("visibilitychange", handleVisibilityChange)
    window.addEventListener('beforeunload', handleBeforeUnload)
    window.addEventListener('unload', handleUnload)
})

onBeforeUnmount(() => {
    // window.removeEventListener('visibilitychange', handleVisibilityChange)
    window.removeEventListener('beforeunload', handleBeforeUnload)
})

*/

</script>

<style lang="less" scoped>
.common-layout {
    height: 100vh;
    width: 100vw;

    .el-header {
        background-color: var(--bgColorBlue);
        color: var(--fontColorWhite);
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 6%;
        width: 100%;
        // border-bottom: #fff solid .0625rem;

        .user-box {
            position: relative;
            width: 6.25rem;
            display: flex;
            justify-content: space-around;
            align-items: center;

            .realname-box {
                font-size: .75rem;
            }

            .logout-box-parent {
                height: 3.125rem;
                width: 4.6875rem;
                border: var(--bgColorBlue) solid .0625rem;
                background-color: var(--fontColorWhite);
                position: absolute;
                top: 2.1875rem;
                z-index: 20;

                .son {
                    height: 50%;
                    line-height: 100%;
                    display: flex;
                    align-items: center;
                    /* 垂直居中 */
                    justify-content: center;
                    font-size: .75rem;
                    color: var(--bgColorBlue);
                }

                .son:hover {
                    background-color: var(--bgColorBlueHover);
                    color: var(--fontColorWhite);
                    cursor: pointer;
                }
            }

            .el-icon:hover {
                cursor: pointer;
            }
        }
    }

    .el-container {
        height: 94%;
        width: 100%;

        .el-aside {
            // background-color: #3e6af8;
            height: 100%;
            width: 15%;
            border-right: var(--borderColor) solid .0625rem;

            .menu-btn-box {
                // background-color: aquamarine;
                height: 5%;
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-around;

                .menu-box,
                .favorites-box,
                .search-box {
                    height: 100%;
                    width: 33.3%;
                    display: flex;
                    align-items: center;
                    justify-content: space-evenly;
                    background-color: #eff1f5;
                    .el-icon {
                        font-size: 1.25rem;
                        // color: #3f77ee;
                        color: var(--bgColorBlue);
                    }

                    .el-icon:hover {
                        font-size: 1.375rem;
                        cursor: pointer;
                    }
                }

                .menu-box.active,
                .favorites-box.active,
                .search-box.active {
                    background-color: var(--fontColorWhite);

                    // color: #165bf0;
                    .el-icon {
                        color: var(--bgColorBlue);
                    }
                }
            }

            .search-info-box,
            .favorites-info-box,
            .menu-info-box {
                height: 95%;
                width: 100%;
                overflow: auto;
                
            }

            .search-info-box {
                .search-input {
                    width: 100%;
                    padding: .3125rem;
                }

                .search-res {
                    width: 100%;
                    padding: .3125rem;
                }
            }
        }

        .el-main {
            height: 100%;
            width: 85%;
            padding: 0;

            .tabs-box {
                height: 4%;
                width: 100%;
                border-bottom: #d9e1f1 solid .0625rem;
                display: flex;
                z-index: 100;
            }

            .session-box {
                height: 96%;
                width: 100%;
            }
        }
    }
}
</style>